package com.coy.web.util;

import com.alibaba.fastjson.JSON;
import com.coy.web.common.consts.WebConsts;
import com.coy.web.common.exception.BizResultCode;
import com.coy.web.common.exception.LoginException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * 注意：基于spring-session实现
 *
 * @Author chenck
 */
public class SessionUtil {

    private static final Logger logger = LoggerFactory.getLogger(SessionUtil.class);

    /**
     * 获取request
     * 注：spring-session对request进行了包装，所以request实际的返回类型是org.springframework.session.web.http.SessionRepositoryFilter
     * .SessionRepositoryRequestWrapper
     *
     * @Param
     */
    public static HttpServletRequest getRequest() {
        HttpServletRequest request =
                ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        return request;
    }

    /**
     * 获取session（session不存在时，则会默认创建session）
     * 注：org.springframework.session.web.http.SessionRepositoryFilter.SessionRepositoryRequestWrapper.HttpSessionWrapper
     * <p>
     * org.springframework.session.web.http.SessionRepositoryFilter.SessionRepositoryRequestWrapper#commitSession()
     * 中保存到redis中的
     *
     * @Param
     */
    public static HttpSession getSession() {
        return getRequest().getSession();
    }

    /**
     * 创建session
     * 注：实际创建的session类型为org.redisson.spring.session.RedissonSessionRepository.RedissonSession
     *
     * @Param
     */
    public static HttpSession getSession(boolean create) {
        return getRequest().getSession(create);
    }

    /**
     * 获取真实IP地址
     *
     * @Param
     */
    public static String getIp() {
        HttpServletRequest request = getRequest();
        if (request == null) {
            return null;
        }
        String ip = request.getHeader("x-forwarded-for");

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("x-forwarded-for");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        return ip.equals("0:0:0:0:0:0:0:1") ? "127.0.0.1" : ip;
    }

    /**
     * 从session获取String值
     *
     * @Author chenck
     */
    public static String getValueString(HttpSession session, String key) {
        Object value = session.getAttribute(key);
        if (null == value) {
            return "";
        }
        return String.valueOf(value);
    }

    public static String getValueString(String key) {
        Object value = getSession().getAttribute(key);
        if (null == value) {
            return null;
        }
        return String.valueOf(value);
    }

    /**
     * 获取请求头中的属性
     *
     * @param
     */
    public static String getHeader(String headerName) {
        return getRequest().getHeader(headerName);
    }

    /**
     * 获取用户信息
     */
    public static com.coy.web.zax.feign.dto.UserInfoDTO getUser(HttpSession session) {
        String userInfo = getValueString(getSession(), WebConsts.SESSION_KEY_USER);
        if (StringUtils.isBlank(userInfo)) {
            return null;
        }
        com.coy.web.zax.feign.dto.UserInfoDTO userInfoDTO = JSON.parseObject(userInfo, com.coy.web.zax.feign.dto.UserInfoDTO.class);
        return userInfoDTO;
    }

    public static com.coy.web.zax.feign.dto.UserInfoDTO getUser() {
        String userInfo = getValueString(getSession(), WebConsts.SESSION_KEY_USER);
        if (StringUtils.isBlank(userInfo)) {
            logger.error("用户登陆不存在或已过期");
            throw new LoginException(BizResultCode.ERR_NOT_LOGIN);
        }
        com.coy.web.zax.feign.dto.UserInfoDTO userInfoDTO = JSON.parseObject(userInfo, com.coy.web.zax.feign.dto.UserInfoDTO.class);
        return userInfoDTO;
    }

}
